package com.team.order.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.team.common.log.annotation.Log;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class GeoToDistrictUtil {
    private static final Logger logger = LoggerFactory.getLogger(GeoToDistrictUtil.class);
    private static final String AMAP_API_KEY = "8cd806401f652203f46bc2f59820e8a6";
    private static final String AMAP_GEO_URL = "https://restapi.amap.com/v3/geocode/regeo?key={key}&location={location}&extensions=base";

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public GeoToDistrictUtil() {
        this.restTemplate = new RestTemplate();
        this.objectMapper = new ObjectMapper();
    }

    /**
     * 根据经纬度获取行政区县信息
     *
     * @param longitude 经度
     * @param latitude  纬度
     * @return 行政区县名称
     * @throws Exception 如果API调用失败或解析失败
     */
    public String getDistrictByGeo(double longitude, double latitude) {
        String location = longitude + "," + latitude;
        String url = AMAP_GEO_URL.replace("{key}", AMAP_API_KEY).replace("{location}", location);

        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                JsonNode rootNode = objectMapper.readTree(response.getBody());
                String status = rootNode.path("status").asText();

                if ("1".equals(status)) {
                    JsonNode regeocode = rootNode.path("regeocode");
                    JsonNode addressComponent = regeocode.path("addressComponent");
                    return addressComponent.path("district").asText();
                } else {
                    logger.error("高德API返回错误状态: {}", rootNode.path("info").asText());
                    return null;
                }
            } else {
                logger.error("高德API调用失败，HTTP状态码: {}", response.getStatusCode());
                return null;
            }
        } catch (Exception e) {
            logger.error("经纬度转行政区县失败: {}", e.getMessage());
            return null;
        }
    }
}
